package com.tju.resource.oauth.controller.tb;

import com.tju.resource.annotation.Log;
import com.tju.resource.business.tb_raw_matl.TbRawMatlService;
import com.tju.resource.model.TbRawMatl;
import com.tju.resource.result.Result;
import com.tju.resource.result.ResultEnum;
import com.tju.resource.result.ResultUtil;
import com.tju.resource.result.SimpleXls;
import com.tju.resource.tool.enum_utils.FunctionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
public class TbRawMatlImportController {

    @Autowired
    TbRawMatlService service;

    private static final String prefix = "rmimpo";

    public static final Map<String, String> keyToBean = new HashMap<>() {{
        put("原材料编号", "rmNo");
        put("原材料名称", "rmName");
        put("原材料外观", "rmExterior");
        put("原材料熔点", "rmMp");
        put("原材料单重", "rmWeight");
        put("原材料重量单位", "rmUnit");
        put("原材料库存", "rmStoke");
        put("备注", "remark");
    }};

    @PreAuthorize("hasAuthority('sys:matl:raw_materials:import')")
    @PostMapping(prefix + "/import")
    @Log(type = FunctionType.Import)
    public Result<Object> importData(@RequestParam Map<String, String> params, @RequestParam("file") MultipartFile file) {
        try {
            return SimpleXls.saveAsBeans(
                    TbRawMatl.class
                    , keyToBean
                    , file.getInputStream()
                    , service::insertTbRawMatl
                    , tbRawMatl -> tbRawMatl.setCreateBy(params.get("createBy")));
        } catch (Exception e) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, e.toString());
        }
    }

}
